<template>
    <div :style="styleObject">
        <div :id="id" :style="styleObject"></div>
    </div>
</template>
<script>
    import {getQiniuUptoken} from '@/api/public';
    import Wangeditor from 'wangeditor'
    import _ from 'lodash'
    function printLog(title, info) {
        window.console && console.log(title, info);
    }
    // 初始化七牛上传
    var uptoken = '';
    function uploadInit() {
        var editor = this;
        var btnId = editor.customUploadBtnId;
        // console.log(btnId)
        var containerId = editor.customUploadContainerId;

        // 创建上传对象
        var uploader = Qiniu.uploader({
            runtimes: 'html5,flash,html4',    //上传模式,依次退化
            browse_button: btnId,       //上传选择的点选按钮，**必需**
            // uptoken_url: 'http://api.yinsoso.com:7979/api/qiniu/uptoken',
            //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
            uptoken : uptoken,
            //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
            unique_names: true,
            // 默认 false，key为文件名。若开启该选项，SDK会为每个文件自动生成key（文件名）
            // save_key: true,
            // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK在前端将不对key进行任何处理
            domain: 'http://img.xianyufanshen.net',
            //bucket 域名，下载资源时用到，**必需**
            container: containerId,           //上传区域DOM ID，默认是browser_button的父元素，
            max_file_size: '100mb',           //最大文件体积限制
            flash_swf_url: '../js/plupload/Moxie.swf',  //引入flash,相对路径
            filters: {
                mime_types: [
                    //只允许上传图片文件 （注意，extensions中，逗号后面不要加空格）
                    {title: "图片文件", extensions: "jpg,gif,png,bmp"}
                ]
            },
            max_retries: 2,                   //上传失败最大重试次数
            dragdrop: true,                   //开启可拖曳上传
            drop_element: 'editor-container',        //拖曳上传区域元素的ID，拖曳文件或文件夹后可触发上传
            chunk_size: '4mb',                //分块上传时，每片的体积
            auto_start: true,                 //选择文件后自动上传，若关闭需要自己绑定事件触发上传
            init: {
                'FilesAdded': function (up, files) {
                    plupload.each(files, function (file) {
                        // 文件添加进队列后,处理相关的事情
                        printLog('on FilesAdded');
                    });
                },
                'BeforeUpload': function (up, file) {
                    // console.log(up);
                    // console.log(uptoken)
                    // 每个文件上传前,处理相关的事情
                    printLog('on BeforeUpload');
                },
                'UploadProgress': function (up, file) {
                    // 显示进度条
                    editor.showUploadProgress(file.percent);
                },
                'FileUploaded': function (up, file, info) {
                    // 每个文件上传成功后,处理相关的事情
                    // 其中 info 是文件上传成功后，服务端返回的json，形式如
                    // {
                    //    "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                    //    "key": "gogopher.jpg"
                    //  }
                    printLog(info);
                    // 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html

                    var domain = up.getOption('domain');
                    var res = $.parseJSON(info);
                    var sourceLink = domain + res.key; //获取上传成功后的文件的Url
                    // console.log(sourceLink)
                    printLog(sourceLink);

                    // 插入图片到editor
                    editor.command(null, 'insertHtml', '<img src="' + sourceLink + '" style="max-width:100%;"/>')
                },
                'Error': function (up, err, errTip) {
                    // console.log(up)
                    //上传出错时,处理相关的事情
                    printLog('on Error',err);
                },
                'UploadComplete': function () {
                    //队列文件处理完毕后,处理相关的事情
                    printLog('on UploadComplete');
                    // 隐藏进度条
                    editor.hideUploadProgress();
                }
                // Key 函数如果有需要自行配置，无特殊需要请注释
                //,
                // 'Key': function(up, file) {
                //     // 若想在前端对每个文件的key进行个性化处理，可以配置该函数
                //     // 该配置必须要在 unique_names: false , save_key: false 时才生效
                //     var key = "";
                //     // do something with key here
                //     return key
                // }
            }
        });
        // domain 为七牛空间（bucket)对应的域名，选择某个空间后，可通过"空间设置->基本设置->域名设置"查看获取
        // uploader 为一个plupload对象，继承了所有plupload的方法，参考http://plupload.com/docs
    }

    export default {
        props: ['id', 'value', 'width', 'height', 'uploadImgUrl', 'disabled', 'mapKey', 'menuFixed', 'pasteFilter', 'codeDefaultLang', 'hideLinkImg', 'uploadParams', 'uploadHeaders', 'isRealtime', 'disabledMenus','useQiniu'],
        data() {
            return {
                menus: [
                    'head',	// 标题
                    'bold',	// 粗体
                    'italic',	// 斜体
                    'underline',  // 下划线
                    'strikeThrough',  // 删除线
                    'forecolor',  // 文字颜色
                    'bgcolor',  // 背景颜色
                    'alignleft',
                    'aligncenter',
                    'alignright',
                    'img',	// 图片
                    'video',
                    'link',	// 链接
                    'unorderlist',	// 无序列表
                    'orderlist',	// 有序列表
                    'quote',	// 引用
                    'table',	// 表格
                    '|',
                    'undo',  // 撤销
                    'redo',  // 重复
                    'fullscreen'	// 全屏
                ],
                styleObject: {
                    width: 'auto',
                    height: 'auto'
                },
                editor: null
            }
        },
        methods: {
            // 设置尺寸
            initSize() {
                if (this.width) {
                    this.styleObject.width = this.width + 'px'
                }
                if (this.height) {
                    this.styleObject.height = this.height + 'px'
                }
            },
            // 创建编辑器
            createEditor() {
                if (!document.getElementById(this.id)) {
                    setTimeout(() => {
                        this.createEditor(this.id)
                    }, 100);
                    return
                }
                this.editor = new Wangeditor(this.id);
                this.editor.config.uploadImgUrl = this.uploadImgUrl;
                this.editor.config.uploadImgFns.onload = (resultText, xhr) => {
                    let originalName = this.editor.uploadImgOriginalName || '';
                    this.$emit('load', originalName, resultText)
                };
                this.editor.config.uploadImgFns.ontimeout = (xhr) => {
                    this.$emit('timeout')
                };
                this.editor.config.uploadImgFns.onerror = (xhr) => {
                    this.$emit('error')
                };
                this.editor.config.uploadImgFileName = 'file';
                this.editor.config.pasteFilter = false;
                if (this.mapKey != undefined) {
                    // 配置地图key，默认空
                    this.editor.config.mapAk = this.mapKey
                }
                if (this.menus != undefined && this.menus instanceof Array && this.menus.length) {
                    // 配置菜单，默认全部，对source进行过滤
                    this.editor.config.menus = this.filterMenu(this.menus)
                } else if (this.disabledMenus) {
                    // 禁用菜单
                    this.editor.config.menus = this.filterDisabledMenu(wangEditor.config.menus, this.disabledMenus)
                } else {
                    this.editor.config.menus = this.filterMenu(wangEditor.config.menus)
                }
                if (this.menuFixed != undefined) {
                    // 配置菜单栏吸顶，默认true
                    this.editor.config.menuFixed = this.menuFixed
                }
                if (this.pasteFilter != undefined) {
                    // 配置粘贴过滤，默认为false
                    this.editor.config.pasteFilter = this.pasteFilter
                }
                if (this.codeDefaultLang != undefined) {
                    // 默认代码类型，默认javascript
                    this.editor.config.codeDefaultLang = this.codeDefaultLang
                }
                if (this.hideLinkImg != undefined) {
                    // 隐藏添加网络图片功能，默认显示
                    this.editor.config.hideLinkImg = this.hideLinkImg
                }
                if (this.uploadParams != undefined && this.uploadParams instanceof Object) {
                    // 上传图片自定义参数
                    this.editor.config.uploadParams = this.uploadParams
                }
                if (this.uploadHeaders != undefined && this.uploadHeaders instanceof Object) {
                    // 上传图片自定义头部
                    this.editor.config.uploadHeaders = this.uploadHeaders
                }
                if (this.useQiniu) {
                    let app = this;
                    this.editor.config.customUpload = true;
                    getQiniuUptoken().then(res => {
                        uptoken = res.data;
                        // console.log("七牛Token："+uptoken)
                        this.editor.config.customUploadInit = uploadInit;
                        this.editor.create();
                    });
                }else{
                    this.editor.create();
                }
                if (this.value) {
                    this.setHtml(this.value)
                }
                if (this.disabled) {
                    this.disable()
                }
                this.listenChange()
            },
            // 筛选编辑器菜单
            filterMenu(menus) {
                return _.map(menus, (item, key) => {
                    if (item === 'source') {
                        return null
                    }
                    return item
                })
            },
            // 筛选不可用菜单
            filterDisabledMenu(menus, disabledMenus) {
                let menusToString = menus.join(',');
                _(disabledMenus).forEach((res) => {
                    menusToString = menusToString.replace(res, '').replace(',,', ',')
                });
                if (menusToString.length && menusToString[0] == ',') {
                    menusToString.substr(1, menusToString.length)
                }
                return menusToString.split(',')
            },
            insertImg(url) {
                this.editor.command(null, 'insertHtml', '<img src=' + url + ' style="max-width:100%;height:auto"/>')
            },
            // 获取内容(html)
            getHtml() {
                return this.editor.$txt.html()
            },
            // 获取内容(纯文本)
            getText() {
                return this.editor.$txt.text()
            },
            // 设置内容(html)
            setHtml(text) {
                // console.log(this.editor.txt.$txt.html("heiehi"))
                this.editor.txt.$txt.html(text)
            },
            // 追加内容(html)
            appendHtml(text) {
                
                this.editor.$txt.append(text)
            },
            // 清空内容
            clear() {
                this.editor.clear()
            },
            // 启用编辑器
            enable() {
                this.editor.enable()
            },
            // 禁用编辑器
            disable() {
                this.editor.disable()
            },
            // 销毁编辑器
            destroy() {
                this.editor.destroy()
            },
            // 恢复编辑器
            undestroy() {
                this.editor.undestroy()
            },
            // 监听内容改变
            listenChange() {
                this.editor.onchange = () => {
                    this.$emit('change');
                    let result = '';
                    if (!this.getText()) {
                        result = this.getHtml()
                    }
                    if (this.isRealtime !== false) {
                        this.$emit('input', result)
                    }
                }
            }
        },
        mounted() {
            this.initSize();
            this.createEditor()
        }
    }
</script>
